package com.zlm.hp.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Build;

import com.zlm.hp.manager.AudioPlayerManager;

/**
 * see: https://github.com/ocwvar/DarkPurple/blob/master/app/src/main/java/com/ocwvar/darkpurple/Services/AudioService.java
 */
public class MediaDeviceConnectedReceiver {

    private BroadcastReceiver receiver;
    private final IntentFilter filter;

    public MediaDeviceConnectedReceiver() {
        filter = new IntentFilter();
        if (Build.VERSION.SDK_INT >= 21) {
            filter.addAction(AudioManager.ACTION_HEADSET_PLUG);
        } else {
            filter.addAction(Intent.ACTION_HEADSET_PLUG);
        }
    }

    /**
     * 注册广播
     * @param context
     */
    public void registerReceiver(Context context) {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())
                        || AudioManager.ACTION_HEADSET_PLUG.equals(intent.getAction())) {

                    int state = intent.getIntExtra("state", -1);
                    if(state==1) {
                        // 如果插入耳机的时候 , 当前有暂停的音频 , 则会继续播放
                        if(AudioPlayerManager.newInstance(context).getPlayStatus() == AudioPlayerManager.PAUSE) {
                            // AppConfigs.isResumeAudioWhenPlugin) { //用户允许耳机连接时重新播放
                            AudioPlayerManager.newInstance(context).playOrPause();
                        }
                    }
                }
            }
        };
        context.registerReceiver(receiver, filter);
    }

    /**
     * 取消注册广播
     */
    public void unregisterReceiver(Context context) {
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }

    public IntentFilter getFilter() {
        return filter;
    }
}
